//
//  JDCateVC.swift
//  LeGou
//
//  Created by 刘亿前 on 2022/9/19.
//

import UIKit
import JXPagingView
import JXSegmentedView

class JDCateVC: ZMViewController, JXSegmentedViewDelegate {

    //MARK: --------------------属性--------------------
    let dataSource: JXSegmentedTitleDataSource = JXSegmentedTitleDataSource()
    var tableHeaderViewHeight: Int = 56
    var headerInSectionHeight: Int = 58
    private var lastScrollingListViewContentOffsetY: CGFloat = 0
    var cateArr = [GoodsCategory]()

    //MARK: --------------------UI控件--------------------
    lazy var pagingView: JXPagingView = preferredPagingView()
    
    lazy var userHeaderView = UIView()
    
    private lazy var searchBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "home_search"), for: .normal)
        btn.setTitle("搜索商品或者粘贴宝贝标题", for: .normal)
        btn.setTitleColor("#999999".zm.hex(), for: .normal)
        btn.layer.cornerRadius = 8
        btn.layer.borderColor = "#DE3F26".zm.hex().cgColor
        btn.layer.borderWidth = 1
        btn.contentHorizontalAlignment = .left
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 0)
        return btn
    }()
    
    lazy var banner: SDCycleScrollView = {
        let view = SDCycleScrollView()
        view.pageDotColor = UIColor.zm.RGBA(r: 255, g: 255, b: 255, a: 0.55)
        view.bannerImageViewContentMode = .scaleAspectFill
        view.autoScrollTimeInterval = 5
        return view
    }()
    
    lazy var vcs = preferredPagingViewVC()

    lazy var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: CGFloat(headerInSectionHeight)))

    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "京东省钱"
        requestCategory()
        bindAction()
    }
    //MARK: --------------------UI--------------------
    func setUI() {
        userHeaderView.addSubview(searchBtn)
        
        dataSource.titles = cateArr.map({return $0.name})
        dataSource.isTitleColorGradientEnabled = true
        dataSource.titleNormalColor = UIColor.zm.color333333()
        dataSource.titleSelectedColor = .white
        dataSource.titleNormalFont = UIFont.systemFont(ofSize: 16)
        dataSource.titleSelectedFont = UIFont.systemFont(ofSize: 16, weight: .medium)
        dataSource.itemSpacing = 26
        
        //配置指示器
        let indicator = JXSegmentedIndicatorBackgroundView()
        indicator.isIndicatorConvertToItemFrameEnabled = true
        indicator.indicatorHeight = 34
        indicator.indicatorColor = Style.mainColor

        segmentedView.backgroundColor = "#F2F3F6".zm.hex()
        segmentedView.delegate = self
        segmentedView.isContentScrollViewClickTransitionAnimationEnabled = false
        segmentedView.dataSource = dataSource
        segmentedView.indicators = [indicator]
        segmentedView.backgroundColor = "#F5F5F5".zm.hex()
        segmentedView.contentEdgeInsetLeft = 22
        segmentedView.contentEdgeInsetRight = 22
        
        ZMUtil.clipCircle(view: segmentedView, Corner: [.topLeft, .topRight], radius: 12)

        pagingView.mainTableView.gestureDelegate = self
        self.view.addSubview(pagingView)
        
        segmentedView.listContainer = pagingView.listContainerView
        
        //扣边返回处理，下面的代码要加上
        pagingView.listContainerView.scrollView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
        pagingView.mainTableView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
        
        addConstraints()
    }
    func addConstraints() {
        pagingView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        searchBtn.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.top.equalTo(10)
            make.right.equalTo(-15)
            make.height.equalTo(36)
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        searchBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            let vc = ZMSearchVC()
            vc.homeSearch = false
            vc.advancedIndex = 1
            self.navigationController?.pushViewController(vc, animated: true)
        }).disposed(by: disposeBag)
    }
    
    func preferredPagingView() -> JXPagingView {
        let page = JXPagingListRefreshView.init(delegate: self)
        return page
    }
    
    func preferredPagingViewVC() -> [JXPagingViewListViewDelegate] {
        var arr = [JXPagingViewListViewDelegate]()
        for i in cateArr {
            let vc1 = JDListVC()
            vc1.openHeaderRefresh = true
            vc1.cid = i.id
            arr.append(vc1)
        }
        return arr
    }
}

extension JDCateVC: JXPagingViewDelegate {
    func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        return vcs[index]
    }
    
    func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int {
        return tableHeaderViewHeight
    }

    func tableHeaderView(in pagingView: JXPagingView) -> UIView {
        return userHeaderView
    }

    func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int {
        return headerInSectionHeight
    }

    func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView {
        return segmentedView
    }

    func numberOfLists(in pagingView: JXPagingView) -> Int {
        return cateArr.count
    }
}

extension JDCateVC: JXPagingMainTableViewGestureDelegate {
    func mainTableViewGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        //禁止segmentedView左右滑动的时候，上下和左右都可以滚动
        if otherGestureRecognizer == segmentedView.collectionView.panGestureRecognizer {
            return false
        }
        return gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
    }
}

// MARK: - Request Action
extension JDCateVC {
    func requestCategory() {
        ZMToast.showActivity()
        let bannerApi = JDDetailAPI.jd_banner.rxRequestNullAble(type: [String].self)
        let cateApi = JDDetailAPI.jd_cate.rxRequestNullAble(type: [GoodsCategory].self)
        Observable.combineLatest(bannerApi,cateApi).subscribe(onNext: { [unowned self] (r1, r2) in
            ZMToast.hiddenActivity()
            if let data = r1 {
                self.tableHeaderViewHeight = 180 + 56
                self.banner.imageURLStringsGroup = data
                self.userHeaderView.addSubview(self.banner)
                self.banner.snp.makeConstraints { make in
                    make.top.equalTo(56)
                    make.left.bottom.right.equalToSuperview()
//                    make.edges.equalToSuperview()
                }
            }
            if let data = r2 {
                self.cateArr = data
            }
            let all = GoodsCategory(name: "全部", id: 0)
            self.cateArr.insert(all, at: 0)
            self.setUI()
        }).disposed(by: disposeBag)
    }
}
